package guo.xungengauth.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 *  此组件是避免feign远程调用丢失cookie数据设计的， 根据RequestContextHolder 得到老请求的cookie，并赋值给新请求的header
 *  此配置类解决了非同步情况下feign远程调用丢失请求头信息
 */
@Configuration
public class FeignInterceptor {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                System.out.println("当前线程id为: "+Thread.currentThread().getId());
                System.out.println("调用远程方法会转到此处");
//  拿到刚进来的请求数据信息
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//  此request就相当于 HttpServletRequest
                if (requestAttributes != null){
                    HttpServletRequest request = requestAttributes.getRequest();
//  得到老请求header里的cookie
                    String cookie = request.getHeader("Cookie");
//  给新请求设置上老请求的cookie
                    requestTemplate.header("Cookie",cookie);
                }
            }
        };
    }
}
